﻿using System;
using System.Data;
using System.Collections;
using System.Web.UI.WebControls;
using NCS.Library;
using NCS.Library.Components.Security;
using NCS.Library.Components.Users;
using NCS.Library.Utilities;

namespace Portal.Administrator.Users
{
	public partial class UserManagement : AuthenticatedControl
	{
        protected void Page_Load(object sender, EventArgs e)
		{
			if (!Page.IsPostBack)
			{
                ArrayList arrLetters = new ArrayList();
				for (char c = 'A'; c <= 'Z'; c++)
				{
					arrLetters.Add(c.ToString());
				}
				arrLetters.Add("All");
				rptLetters.DataSource = arrLetters;
				rptLetters.ItemDataBound += new RepeaterItemEventHandler(rptLetters_ItemDataBound);
				rptLetters.DataBind();
                this.ViewState["DropDownPageItems"] = 10;
			}
		}

        private void rptLetters_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                LinkButton lnkLetter = (LinkButton)e.Item.FindControl("lnkLetter");
                lnkLetter.Text = e.Item.DataItem.ToString();
                lnkLetter.CommandArgument = e.Item.DataItem.ToString();
            }
        }
        public void rptLetters_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "Alpha")
            {
                if (ConvertUtility.ToString(e.CommandArgument) != "All")
                {
                    ViewState["Alphabet"] = e.CommandArgument;
                }
                else
                {
                    ViewState["Alphabet"] = "";
                }
            }
        }
        protected void dtgUsers_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
                ImageButton btnImgDeleteUser = (ImageButton)e.Row.FindControl("btnImgDeleteUser");
                if (btnImgDeleteUser.CommandArgument == "48")
                {
                    //Admin => ko duoc xoa
                    btnImgDeleteUser.Visible = false;

                    CheckBox chkUser = (CheckBox)e.Row.FindControl("DeleteThis");
                    chkUser.Visible = false;
                }
			    ImageButton btnImgManageProfile = (ImageButton)e.Row.FindControl("btnImgManageProfile");
                ImageButton btnImgManagePassword = (ImageButton)e.Row.FindControl("btnImgManagePassword");
                ImageButton btnImgUserPermision = (ImageButton)e.Row.FindControl("btnImgUserPermision");
                btnImgUserPermision.Visible = this.drl_usertype.SelectedValue == "1";
                Label lblKey = (Label)e.Row.FindControl("lblKey");
			    
                btnImgDeleteUser.OnClientClick = MiscUtility.MSG_DELETE_CONFIRM;    
          
				DataRowView curData = (DataRowView)e.Row.DataItem;

                if ((lblKey.Text == "1") || (e.Row.Cells[2].Text == AppEnv.ADMIN_EMAIL))
                {
                    if (CurrentUser.Email != AppEnv.ADMIN_EMAIL)
                    {
                        e.Row.Visible = false;
                    }
                    else
                    {
                        e.Row.Visible = true;
                    }
                }

                
			}
		}
		protected void dtgUsers_RowCommand(object sender, GridViewCommandEventArgs e)
		{
			int userId = ConvertUtility.ToInt32(e.CommandArgument);
			switch (e.CommandName)
			{
                case "manageprofile":
                    {
                        UserInfo userinfo = UserController.GetUser(userId);
                        if (userinfo != null)
                        {
                            if (userinfo.UserType == 1)
                            {
                                Response.Redirect(AppEnv.AdminUrlParams("manageprofile") + "&uid=" + userId);
                            }
                            else
                            {
                                Response.Redirect(AppEnv.AdminUrlParams("createuserdaibieu") + "&uid=" + userId);
                            }
                        }
                        break;
                    }
				case "managepassword":
                    Response.Redirect(AppEnv.AdminUrlParams("managepassword") + "&uid=" + userId);
					break;
				case "userpermision":
                    Response.Redirect(AppEnv.AdminUrlParams("userpermision") + "&uid=" + userId);
					break;
				case "deleteuser":
					try
					{
						UserController.DeleteUser(userId);
						this.lblUpdateStatus.Text = MiscUtility.MSG_UPDATE_SUCCESS;
                        this.AddLog("User", " try delete user " + userId + " success");
					}
					catch (Exception ex)
					{
						this.lblUpdateStatus.Text = ex.Message;
                        this.AddLog("User", " try delete user " + userId + " error: " + ex.Message);
					}
					break;
				default:
					break;
			}
		}
		protected void btnAddUser_Click(object sender, EventArgs e)
		{
            Response.Redirect(AppEnv.AdminUrlParams("createuser"));
		}
        protected void btnAddUserDaiBieu_Click(object sender, EventArgs e)
        {
            //Response.Redirect(AppEnv.AdminUrlParams("createuserdaibieu"));
        }
		protected override void OnPreRender(EventArgs e)
		{
			base.OnPreRender(e);
            DataTable dtUsers;
            if (!CurrentUser.IsAdmin && !CurrentUser.IsSuperAdmin)
            {
                dtUsers = UserController.GetUsersByUser(txtKeyword.Text, dropSearchBy.SelectedValue, ConvertUtility.ToString(ViewState["Alphabet"]), CurrentUser.UserID, ConvertUtility.ToInt32(AppEnv.PortalId()), Convert.ToInt16(this.drl_usertype.SelectedValue));
            }
            else
            {
                dtUsers = UserController.GetUsers(txtKeyword.Text, dropSearchBy.SelectedValue, ConvertUtility.ToString(ViewState["Alphabet"]), ConvertUtility.ToInt32(AppEnv.PortalId()), Convert.ToInt16(this.drl_usertype.SelectedValue));
            }

            //-------sort----------
            DataView dv = new DataView(dtUsers);
            if (ViewState["sortExpression"] != null && ViewState["sortExpression"].ToString() != string.Empty)
            {
                dv.Sort = ViewState["sortExpression"].ToString();
            }

            if (ViewState["sortDirection"] != null && ViewState["sortDirection"].ToString() == "Desc")
            {
                dv.Sort = ViewState["sortExpression"].ToString() + " " + ViewState["sortDirection"].ToString();
            }
            //--------sort-------------

            dtgUsers.DataSource = dv;
			dtgUsers.RowDataBound += new GridViewRowEventHandler(dtgUsers_RowDataBound);
			dtgUsers.DataBind();
		}
        protected void btnDeleteSelected_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow gv in dtgUsers.Rows)
            {
                CheckBox deleteChkBxItem = (CheckBox)gv.FindControl("DeleteThis");
                if (deleteChkBxItem.Checked)
                {
                    string strTemp = ((Label)gv.FindControl("lblKey")).Text.ToString();
                    UserController.DeleteUser(Convert.ToInt32(strTemp));
                    this.AddLog("User", " try delete user " + strTemp + " success");
                    dtgUsers.DataBind();
                }
            }
        }
        protected void dtgUsers_Sorting(object sender, GridViewSortEventArgs e)
        {
          if (ViewState["sortDirection"] == null || ViewState["sortDirection"].ToString()=="")
            {
                ViewState["sortDirection"] = "Desc";
            }
            else if (ViewState["sortDirection"].ToString() == "Desc")
            {
                ViewState["sortDirection"] = "";
            }
            ViewState["sortExpression"] = e.SortExpression;
           
        }
        protected void dtgUsers_PreRender(object sender, EventArgs e)
        {
            if (dtgUsers.BottomPagerRow != null)
            {
                ((Label)dtgUsers.BottomPagerRow.FindControl("lbTotalPages")).Text = dtgUsers.PageCount.ToString();

                //This makes the first and last button disappear when on the first and last pages.
                ((LinkButton)dtgUsers.BottomPagerRow.FindControl("lbtnFirst")).Visible = dtgUsers.PageIndex != 0;
                ((LinkButton)dtgUsers.BottomPagerRow.FindControl("lbtnLast")).Visible = dtgUsers.PageCount != (dtgUsers.PageIndex + 1);

                DropDownList ddlistPageof = (DropDownList)dtgUsers.BottomPagerRow.FindControl("ddlPageItems");
                ddlistPageof.SelectedIndex = ddlistPageof.Items.IndexOf(ddlistPageof.Items.FindByValue(this.ViewState["DropDownPageItems"].ToString()));
                DropDownList ddlistPageno = (DropDownList)dtgUsers.BottomPagerRow.FindControl("ddlNumberPages");
                ddlistPageno.Items.Clear();
                for (int i = 1; i <= dtgUsers.PageCount; i++)
                {
                    ListItem liTemp = new ListItem();
                    liTemp.Text = i.ToString();
                    liTemp.Value = i.ToString();
                    ddlistPageno.Items.Add(liTemp);
                }
                if (dtgUsers.PageCount != 0)
                {
                    ddlistPageno.SelectedIndex = dtgUsers.PageIndex;
                    ddlistPageno.DataBind();
                }
            }
        }
        protected void ddlNumberPages_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList ddlistPageno = (DropDownList)dtgUsers.BottomPagerRow.FindControl("ddlNumberPages");
            dtgUsers.PageIndex = Convert.ToInt32(ddlistPageno.SelectedValue) - 1;

        }
        protected void dtgUsers_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            dtgUsers.PageIndex = e.NewPageIndex;
        }
        protected void ddlPageItems_SelectedIndexChanged(object sender, EventArgs e)
        {
            int pageItems = Convert.ToInt32(((DropDownList)sender).SelectedValue);
            this.dtgUsers.PageSize = pageItems;
            this.ViewState["DropDownPageItems"] = pageItems;
        }
        protected void btnSearch_Click(object sender, EventArgs e)
        {

        }
	}
}